package cn.oms.file.provider.service.impl;

import cn.oms.file.api.service.IQRCodeServic;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;

/**
 * 二维码服务
 */

@RestController
@Service
@Slf4j
public class QRCodeServiceImpl implements IQRCodeServic {


    @Value("${oms.file.image.qrcode.upload.path}")
    public String fileUploadPath;

    @Value("${oms.file.resource.image.qrcode.host}")
    public String resourceHost;

    /**
     * 生成二维码图片
     * 返回前端查看路径
     */
    @Override
    public String generateQRCodeImage(String text, String format, int width, int height, String fileName) {

        // 拼接前端访问的路径
        String resourcePath = resourceHost + fileName+"."+format;

        // 文件路径拼接
        // D:/omsFile/image/QECode/文件名.文件格式
        String PATH = fileUploadPath+fileName+"."+format;

        // 生成二维码图片输出流
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        //存储乱码问题
        HashMap map=new HashMap();
        map.put(EncodeHintType.CHARACTER_SET,"UTF-8");

        BitMatrix bitMatrix = null;
        try {

            //生成二维码信息对象
            bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height,map);
        } catch (WriterException e) {
            e.printStackTrace();
        }

        try {
            //将二维码写入指定路径的文件中
            MatrixToImageWriter.writeToPath(bitMatrix, format, Paths.get(PATH));
            log.info("二维码生成成功！！！文件地址：{}",PATH);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回资源访问路径
        return resourcePath;

    }

}
